package com.zhangx.datastructure.string;

/**
 * @ClassName MyString
 * @Description 串
 * P127
 * @Author zhangx
 * @Date 2021/1/5 8:40
 **/
public class MyString {

    public static String m = "zhangxu";
    public static String[] m2 = new String[]{"7","z","x","a","n","g","x","u"};
    public static String[] t2 = new String[]{"2","x","u"};

    public int index(String m,String t,int pos){
        if (pos > 0){

            int l1 = m.length();
            int l2 = t.length();

            int i = pos;
            while (i<=l1-l2+1){

                String cmp = m.substring(i,i+l2);
                if (cmp.equals(t)){
                    return i;
                }else {

                    i++;
                }

            }
        }

        return -1;

    }

    /**
     * 书上写法是对的
     *
     * @param m
     * @param t
     * @param pos
     * @return
     */
    public int index2(String[] m,String[] t, int pos){
        int ml = Integer.parseInt(m[0]);
        int tl = Integer.parseInt(t[0]);

        int i = pos;
        int j = 1;
        while (i <= ml && j <= tl){

            if (m[i].equals(t[j])){
                j++;
                i++;
            }else {
//                如果不是全字符匹配上
//                why这个，会回到上次匹配的首位的下一位，当t字符串长度>2时候，比i++循环次数少
//                如果 i++会浪费一些
                i = i - j + 2;
//                j 回退到第一个字符
                j = 1;
            }

            if (j > tl){
//                全字符匹配上
                return i-tl;
            }

        }

        return -1;
    }

    public static void main(String[] args) {
        MyString myString = new MyString();
        System.out.println(myString.index(m,"xu",1));
        System.out.println(myString.index2(m2,t2,1));
    }
}
